<template>
  <div class="box">
    <div class="f jcsb aic header">
      <el-icon
        class="ml30 mr25 pointer"
        color="#3E4850"
        :size="20"
        @click="back"
        ><Back
      /></el-icon>
      <div class="f14 f1 text-center mr30 pr30">
        {{ title }}
      </div>
    </div>

    <div v-if="hasExercise" class="main no-select">
      <div class="paper relative">
        <div class="pt30 mb10 f aic jcsb">
          <div class="f aic">
            {{ currQuestion }}.
            <el-tag
              v-show="question.questionType == 1"
              type="danger"
              class="ml10"
              size="small"
            >
              单选题
            </el-tag>
            <el-tag
              v-show="question.questionType == 2"
              type="danger"
              class="ml10"
              size="small"
            >
              多选题
            </el-tag>
            <el-tag
              v-show="question.questionType == 3"
              type="danger"
              class="ml10"
              size="small"
            >
              判断题
            </el-tag>
            <!-- <el-tag
              v-show="question.questionType == 4"
              type="danger"
              class="ml10"
              size="small"
            >
              简答题
            </el-tag> -->
          </div>
          <!-- <div
            class="pointer"
            @click="question.isCollect = !question.isCollect"
          >
            <svg-icon
              v-if="question.isCollect"
              icon-class="star-fill"
              size="20"
            />
            <svg-icon v-else icon-class="star" size="20" />
          </div> -->
        </div>
        <div class="line40 f18" v-html="question.questionTitle"></div>
        <div class="mt20 f18">
          <div
            v-if="question.questionType != 3"
            class="f aic mb15 pointer"
            v-for="(item, index) in answerOption"
            :key="index"
            @click="addAnswerOption(item)"
            :class="{
              'select-option':
                question.stuAnswers.indexOf(item.optionLabel) !== -1,
            }"
          >
            <div class="answer-sign f jcc mr10">{{ item.optionLabel }}</div>
            {{ item.content }}
            <div class="ml20" v-if="question.isSubmit">
              <svg-icon v-if="item.rightState" icon-class="right" size="25" />
              <svg-icon v-else icon-class="error" size="25" />
            </div>
          </div>
          <!-- 判断 -->
          <div
            v-else
            class="f aic mb15 pointer"
            v-for="(item, i) in givenOption"
            :key="i"
            @click="addAnswerOption(item)"
            :class="{
              'select-option': question.stuAnswers.indexOf(item.content) !== -1,
            }"
          >
            <div class="answer-sign f jcc mr10">{{ item.optionLabel }}</div>
            {{ item.content }}
            <div class="ml20" v-if="question.isSubmit">
              <svg-icon
                v-if="
                  strToObj(question.rightAnswers).indexOf(item.content) > -1
                "
                icon-class="right"
                size="25"
              />
              <svg-icon v-else icon-class="error" size="25" />
            </div>
          </div>
        </div>

        <div v-if="question.isSubmit">
          <div class="f answer-bg">
            <div class="f1 f column jcc aic">
              <div class="bold C12c83a mb10 f20">
                {{ strToObj(question.rightAnswers)?.join(",") }}
              </div>
              <div class="f14">正确答案</div>
            </div>
            <div class="f1 f column jcc aic">
              <div class="bold Cda0007 mb10 f20">
                {{ question.stuAnswers.join(",") }}
              </div>
              <div class="f14">你的答案</div>
            </div>
          </div>
          <!-- 解析 -->
          <div>
            <div class="analysis-title mt40 mb20 ml10">解析</div>
            <div class="line30">
              <div>{{ question.answersOntleed }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="mt30 text-center">
        <el-button
          type="danger"
          color="#F02323"
          plain
          @click="currQuestion -= 1"
          :disabled="currQuestion == 1"
          >上一题</el-button
        >
        <el-button
          type="danger"
          color="#F02323"
          @click="submit"
          :disabled="
            (question.stuAnswers && question.stuAnswers.length == 0) ||
            question.isSubmit
          "
        >
          提 交
        </el-button>
        <el-button
          type="danger"
          color="#F02323"
          @click="currQuestion += 1"
          :disabled="currQuestion == questionList.length"
          >下一题</el-button
        >
      </div>
    </div>
    <div v-else>
      <el-empty description="暂无习题" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
import {
  Back,
  Setting,
  DocumentChecked,
  CaretTop,
  CaretBottom,
} from "@element-plus/icons-vue";
import { onMounted } from "vue";
import {
  getCourseAllExercise,
  getCourseWrongExercise,
  saveCourseExercise,
} from "@/api/course";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const courseId = ref();
const hasExercise = ref(true);
const title = ref("");
const questionList = ref([]);
const currQuestion = ref(1);
const question = ref({});
const answerOption = ref([]);
const givenOption = ref([
  {
    optionLabel: "A",
    content: "正确",
  },
  {
    optionLabel: "B",
    content: "错误",
  },
]);
const userInfo = JSON.parse(localStorage.getItem("userInfo"));

const getCourseAllExerciseData = () => {
  getCourseAllExercise(courseId.value).then((res) => {
    title.value = "《" + res.data.courseName + "》课程练习";
    if (res.data.coursePaperDetailList.length > 0) {
      hasExercise.value = true;
      questionList.value = res.data.coursePaperDetailList.map((item) => {
        item.stuAnswers = [];
        item.rightOption = [];
        item.errorOption = [];
        item.isSubmit = false;
        return item;
      });
      question.value = questionList.value[currQuestion.value - 1];
      answerOption.value = JSON.parse(
        questionList.value[currQuestion.value - 1].questionAnswers
      );
    } else {
      hasExercise.value = false;
    }
  });
};

const getCourseWrongExerciseData = () => {
  const params = {
    stuId: userInfo.userId,
  };
  getCourseWrongExercise(courseId.value, params).then((res) => {
    title.value = "《" + res.data.courseName + "》错题练习";
    if (res.data.coursePaperDetailList.length > 0) {
      hasExercise.value = true;
      questionList.value = res.data.coursePaperDetailList.map((item) => {
        item.stuAnswers = [];
        item.rightOption = [];
        item.errorOption = [];
        item.isSubmit = false;
        return item;
      });
      question.value = questionList.value[currQuestion.value - 1];
      answerOption.value = JSON.parse(
        questionList.value[currQuestion.value - 1].questionAnswers
      );
    } else {
      hasExercise.value = false;
    }
  });
};

const addAnswerOption = (item) => {
  if (!question.value.isSubmit) {
    if (question.value.questionType == 1) {
      // 单选
      question.value.stuAnswers[0] = item.optionLabel;
    } else if (question.value.questionType == 2) {
      // 多选
      if (question.value.stuAnswers.indexOf(item.optionLabel) !== -1) {
        question.value.stuAnswers = question.value.stuAnswers.filter(
          (option) => option !== item.optionLabel
        );
      } else {
        question.value.stuAnswers.push(item.optionLabel);
      }
    } else if (question.value.questionType == 3) {
      // 判断
      question.value.stuAnswers[0] = item.content;
    }
  }
};

const submit = () => {
  question.value.isSubmit = true;
  question.value.stuAnswers.sort();
  // 获取答案分类对象
  const obj = findIntersection(
    JSON.parse(question.value.rightAnswers),
    question.value.stuAnswers
  );
  // 正确选项的数组
  question.value.rightOption = obj.rightAnswer;
  // 错选和未选的数组
  question.value.errorOption = obj.errSelectedArr.concat(obj.unselectedArr);

  const answer = [
    {
      questionId: question.value.questionId,
      answer: question.value.stuanswers,
      isRight: question.value.errorOption.length > 0 ? false : true,
    },
  ];

  const params = {
    stuId: userInfo.userId,
    paperDetailId: question.value.paperDetailId,
    stuAnswers: JSON.stringify(answer),
    isRight: question.value.errorOption.length > 0 ? 0 : 1,
    createBy: userInfo.userName,
    updateBy: userInfo.userName,
  };
  saveCourseExercise(params).then((res) => {
    // ElMessage.success("提交成功");
  });
};

watch(currQuestion, (newVal, oldVal) => {
  question.value = questionList.value[newVal - 1];
  answerOption.value = JSON.parse(
    questionList.value[newVal - 1].questionAnswers
  );
});

onMounted(() => {
  // courseId.value = 707;
  courseId.value = route.query.id;
  if (route.query.type == "wrong") {
    getCourseWrongExerciseData();
  } else {
    getCourseAllExerciseData();
  }
});

const back = () => {
  history.back();
};

const findIntersection = (rightArr, myArr) => {
  // 选对的数组
  const rightAnswer = rightArr.filter((item) => myArr.includes(item));

  // 未选择的正确选项数组
  const unselectedArr = rightArr.filter((item) => !myArr.includes(item));

  // 选错的数组
  const errSelectedArr = myArr.filter((item) => !rightArr.includes(item));

  return {
    rightAnswer,
    unselectedArr,
    errSelectedArr,
  };
};

const strToObj = (str) => {
  if (str) return JSON.parse(str);
};
</script>
<style lang="scss" scoped>
.box {
  background: #f5f7fa;
  height: 100vh;
  .header {
    height: 60px;
    background: #fff;
    padding: 0 130px;
    .setting {
      color: #3c464f;
    }
  }
  .main {
    padding: 0 130px 35px;
    margin-top: 20px;
    height: calc(100% - 80px);
    .paper {
      background: #fff;
      border-radius: 10px;
      width: 100%;
      height: calc(100% - 65px);
      min-height: 500px;
      padding: 0 20px;
      .answer-sign {
        width: 32px;
        height: 32px;
        border: 1px solid #d6d6d6;
        border-radius: 50%;
        color: #6c6c6c;
        line-height: 30px;
      }
      .select-option {
        color: #4775fe;
        width: 100%;
        .answer-sign {
          background: #4775fe;
          border-color: #4775fe;
          color: #fff;
        }
      }
      .answer-bg {
        background: #f7f9fc;
        border: 1px solid #ffffff;
        border-radius: 10px;
        height: 90px;
        margin-top: 70px;
      }
      .C12c83a {
        color: #12c83a;
      }
      .Cda0007 {
        color: #da0007;
      }

      .analysis-title {
        padding-left: 25px;
        background: url("@/assets/images/analysis.png") left center no-repeat;
      }
      .line30 {
        line-height: 30px;
      }

      .question-num-box {
        width: calc(100% - 40px);
        transition: height 0.5s ease;
        overflow: hidden;
        .question-num {
          width: 32px;
          height: 32px;
          border-radius: 5px;
          background: #f5f7fa;
          color: #3f4952;
          line-height: 32px;
          text-align: center;
          font-size: 14px;
          flex-shrink: 0;
          margin: 10px 20px 10px 0;
          cursor: pointer;
        }
        .error-question {
          background: rgba(240, 35, 35, 0.5) !important;
          color: #fff;
        }
        .current-question {
          background: #f02323 !important;
          color: #fff;
        }
      }
    }
  }
  .line40 {
    line-height: 40px;
  }
  button {
    width: 100px;
  }
}
</style>
